/* eslint-disable react-refresh/only-export-components */
import { NavBar, SearchBar } from 'antd-mobile'
import { useNavigate } from 'react-router-dom'
import CityTop from './components/CityTop'
import CityList from './components/CityList'
import { getCityPositionApi, getCityApi } from '../../api/city'
import { setCity } from '../../store/slice/ticketSlice'
import { useDispatch } from 'react-redux'
import { searchCityApi } from '../../api/city'
import { useFd } from '../../hooks'
import SearchList from './components/SearchList'
import { useState } from 'react'
import SearchHistory from './components/SearchHistory'
import AuthHoc from '../../components/AuthHoc'
import styles from './css/city.module.css'

function City() {
  const nav = useNavigate()
  const dispatch = useDispatch()
  const fd = useFd()
  const [searchResult, setSearchResult] = useState([])
  // 搜索关键字
  const [kw, setKw] = useState('')

  // 把用户点击的城市，存入全局
  const saveCity = (propName, city) => {
    dispatch(setCity({ propName, city }))
    nav(-1)
  }

  // 监听搜索框内容的变化，通过形参拿到变化后的新值
  const changeFn = (kw) => {
    setKw(kw)
    if (kw.length !== 0) {
      // 如果搜索关键词的 length 不为 0，则调用搜索的函数
      search(kw)
    } else {
      // 否则，把搜索的结果清空
      setSearchResult([])
    }
  }

  // 使用 fd 对搜索的方法进行防抖
  const search = fd(async (kw) => {
    const { data: res } = await searchCityApi(kw)
    setSearchResult(res)
  })

  return (
    <div>
      {/* 顶部的导航 + 搜索区域 */}
      <div className={styles.navbar}>
        <NavBar onBack={() => nav(-1)}>
          <SearchBar
            placeholder="请输入城市关键字"
            onChange={changeFn}
          />
        </NavBar>
      </div>

      <div style={{ display: kw.length === 0 ? 'none' : 'block' }}>
        {/* 搜索结果 */}
        <SearchList
          list={searchResult}
          saveCity={saveCity}
        />

        {/* 搜索历史 */}
        <SearchHistory saveCity={saveCity} />
      </div>

      <div style={{ display: kw.length !== 0 ? 'none' : 'block' }}>
        {/* 城市定位 + 热门城市 */}
        <CityTop saveCity={saveCity} />

        {/* 城市列表 */}
        <CityList saveCity={saveCity} />
      </div>
    </div>
  )
}

export default AuthHoc(City)

export const loader = async () => {
  // 调用接口，获取城市定位
  const { data: res } = await getCityPositionApi()
  // 调用接口，获取热门城市 和 城市列表数据
  const { data: res2 } = await getCityApi()

  // return { location: '定位的城市名', hot: '热门城市的数组', list: '所有城市的数组' }
  return { location: res.city, hot: res2.hotCities, list: res2.cityList }
}
